<template>
  <div class="AddOrUpdate_main andonSet_container add_container">
    <div class="main_main">
      <div class="main_main_left">
        <div class="main_main_left_header">

          <el-select v-model="pageData.deviceType" placeholder="请选择">
            <el-option label="数采设备" :value="1" />
            <el-option label="普通设备" :value="2" />
          </el-select>
        </div>
        <div class="main_main_left_content">
          <div
            v-for="(item,index) in deviceList"
            :key="index"
            class="main_main_left_content_item"
            draggable="true"
            unselectable="on"
            :valu="item.id"
            @drag="drag"
            @dragend="dragend"
          >
            <div v-if="item.avatarUrl&&item.avatarUrl.length>0" class="left_content_item_left">
              <img :src="item.avatarUrl" style="object-fit: contain;">
            </div>
            <div class="left_content_item_right">
              <div class="left_content_item_right_top">{{ item.code }}</div>
              <div class="left_content_item_right_bottom">{{ item.name }}</div>
            </div>
          </div>
        </div>
      </div>
      <div id="content" class="main_main_right">
        <grid-layout
          ref="gridlayout"
          :layout.sync="layout"
          :col-num="200"
          :row-height="10"
          :is-draggable="true"
          :is-resizable="true"
          :is-mirrored="false"
          :auto-size="false"
          :vertical-compact="false"
          :margin="[10, 10]"
          :use-css-transforms="true"
        >

          <grid-item
            v-for="item in layout"
            :key="item.i"
            :x="item.x"
            :y="item.y"
            :w="item.w"
            :h="item.h"
            :i="item.i"
          >

            <div class="grid-item-container">
              <div class="grid-item-container-line1" />
              <div class="grid-item-container-line2">{{ (normalList.filter(item2=>item2.id ==item.deviceId ))[0].code }}</div>
              <div class="grid-item-container-line3">{{ (normalList.filter(item2=>item2.id ==item.deviceId ))[0].name }}</div>
              <div class="grid-item-container-line4">
                <div v-if="(normalList.filter(item2=>item2.id ==item.deviceId ))[0].avatarUrl" class="grid-item-container-line4-img">
                  <img :src="(normalList.filter(item2=>item2.id ==item.deviceId ))[0].avatarUrl" style="object-fit: contain;">
                </div>
                <div class="grid-item-container-line4-status" :class="((normalList.filter(item2=>item2.id ==item.deviceId ))[0].avatarUrl)?'':'noPic'">设备状态</div>
              </div>
              <span class="remove" @click="removeItem(item.i)">x</span>
            </div>
          </grid-item>
        </grid-layout>
      </div>
      <div class="backgroundImage_div" :style="{ backgroundImage: 'url(' + row.fileUrl + ')' }" />

    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate } from '@/api/equipmentManage/andonManage/andonManage'
import { list as getNormalDevice } from '@/api/equipmentManage/baseInfo/equipmentInfo'

import { list as getCollectionDevice } from '@/api/equipmentManage/equipmentReport/equipmentStatusReport'
import VueGridLayout from 'vue-grid-layout'

const mouseXY = { 'x': null, 'y': null }
const DragPos = { 'x': null, 'y': null, 'w': 1, 'h': 1, 'i': null }

export default {
  name: 'AddOrUpdate',
  components: {
    GridLayout: VueGridLayout.GridLayout,
    GridItem: VueGridLayout.GridItem
  },
  props: {
    layerid: {},
    row: {}
  },
  data() {
    return {
      formData: {
        code: '',
        name: '',
        fileName: '',
        fileRealName: '',
        fileUrl: '',
        remark: ''
      },
      pageData: {
        deviceType: 2,
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      deviceList: [],
      normalList: [],
      collectionList: [],
      layout: []
    }
  },
  watch: {
    'pageData.deviceType'(val) {
      if (val == 1) {
        this.getCollectionDevice()
      }
      if (val == 2) {
        this.getNormalDevice()
      }
    }
  },
  mounted() {
    this.getNormalDevice()

    document.addEventListener('dragover', function(e) {
      mouseXY.x = e.clientX
      mouseXY.y = e.clientY
    }, false)
  },
  methods: {
    getNormalDevice() {
      getNormalDevice(this.pageData).then(res => {
        this.normalList = res.data
        this.deviceList = res.data
      })
    },
    getCollectionDevice() {
      getCollectionDevice(this.pageData).then(res => {
        const cacheData = this.$deepClone(res.data)
        cacheData.forEach((item, index) => {
          item.id = item.deviceId
          if (index == cacheData.length - 1) {
            this.collectionList = cacheData
            this.deviceList = cacheData
          }
        })
      })
    },
    onSubmit() {
      const cacheRow = this.$deepClone(this.row)
      cacheRow.chart = JSON.stringify(this.layout)
      addOrUpdate(cacheRow).then(res => {
        this.$message({
          message: res.msg,
          type: 'success'
        })
        this.$layer.close(this.layerid) // 关闭弹框
        this.$parent.getList() // 调用父组件的刷新方法
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    drag: function(e) {
      const parentRect = document.getElementById('content').getBoundingClientRect()
      let mouseInGrid = false
      if (((mouseXY.x > parentRect.left) && (mouseXY.x < parentRect.right)) && ((mouseXY.y > parentRect.top) && (mouseXY.y < parentRect.bottom))) {
        mouseInGrid = true
      }
      if (mouseInGrid == true && (this.layout.findIndex(item => item.i == 'drop')) == -1) {
        this.layout.push({
          x: (this.layout.length * 2) % (this.colNum || 12),
          y: this.layout.length + (this.colNum || 12), // puts it at the bottom
          w: 1,
          h: 1,
          i: 'drop'
        })
      }
      const index = this.layout.findIndex(item => item.i == 'drop')
      if (index !== -1) {
        try {
          this.$refs.gridlayout.$children[this.layout.length].$refs.item.style.display = 'none'
        } catch {
        }
        const el = this.$refs.gridlayout.$children[index]
        el.dragging = { 'top': mouseXY.y - parentRect.top, 'left': mouseXY.x - parentRect.left }
        const new_pos = el.calcXY(mouseXY.y - parentRect.top, mouseXY.x - parentRect.left)
        if (mouseInGrid == true) {
          this.$refs.gridlayout.dragEvent('dragstart', 'drop', new_pos.x, new_pos.y, 1, 1)
          DragPos.i = String(index)
          DragPos.x = this.layout[index].x
          DragPos.y = this.layout[index].y
        }
        if (mouseInGrid == false) {
          this.$refs.gridlayout.dragEvent('dragend', 'drop', new_pos.x, new_pos.y, 1, 1)
          this.layout = this.layout.filter(obj => obj.i !== 'drop')
        }
      }
    },
    dragend: function(e) {
      const parentRect = document.getElementById('content').getBoundingClientRect()
      let mouseInGrid = false
      if (((mouseXY.x > parentRect.left) && (mouseXY.x < parentRect.right)) && ((mouseXY.y > parentRect.top) && (mouseXY.y < parentRect.bottom))) {
        mouseInGrid = true
      }
      if (mouseInGrid == true) {
        // alert(`Dropped element props:\n${JSON.stringify(DragPos, ['x', 'y', 'w', 'h'], 2)}`)
        this.$refs.gridlayout.dragEvent('dragend', 'drop', DragPos.x, DragPos.y, 1, 1)
        this.layout = this.layout.filter(obj => obj.i !== 'drop')
        // UNCOMMENT below if you want to add a grid-item
        this.layout.push({
          x: DragPos.x,
          y: DragPos.y,
          w: 40,
          h: 6,
          i: DragPos.i,
          deviceId: e.target.attributes.valu.value
        })
        this.$refs.gridLayout.dragEvent('dragend', DragPos.i, DragPos.x, DragPos.y, 1, 1)
        try {
          this.$refs.gridLayout.$children[this.layout.length].$refs.item.style.display = 'block'
        } catch {
        }
      }
    },
    removeItem: function(val) {
      const index = this.layout.map(item => item.i).indexOf(val)
      this.layout.splice(index, 1)
    }

  }
}
</script>

<style lang="less" scoped>
.andonSet_container{
  .main_main{
    display: flex;padding-top: 10px;
    .main_main_left{
      width: 200px;
      height: 100%;
      margin: 0 20px;
      background-color: #E5F1FF;
      .main_main_left_header{

      }
      .main_main_left_content{
        height: calc(100% - 50px);
        overflow-y: auto;
      }
      .main_main_left_content_item{
        display: flex;
        height: 60px;
        border-radius: 5px;
        margin: 10px 10px;
        background-color: white;

        .left_content_item_left{
          margin: 5px;
          width: 40px;
          height: calc(100% - 10px);
          img{
            width: 100%;
            height: 100%;
          }
        }
        .left_content_item_right{
          margin-left: 10px;
          width: calc(100% - 50px);
          margin-top: 5px;
          margin-bottom: 5px;
          .left_content_item_right_top{
            width: 100%;
            height: 50%;
            overflow:hidden; //超出的文本隐藏
            text-overflow:ellipsis; //溢出用省略号显示
            white-space:nowrap; //溢出不换行
            display: flex;justify-content: flex-start;align-items: center;
          }
          .left_content_item_right_bottom{
            width: 100%;
            height: 50%;
            overflow:hidden; //超出的文本隐藏
            text-overflow:ellipsis; //溢出用省略号显示
            white-space:nowrap; //溢出不换行
            display: flex;justify-content: flex-start;align-items: center;
          }
        }
      }
      .main_main_left_content_item:hover{
        background-color: rgba(56, 123, 252, 0.5);
        color: white;
      }
    }
    .main_main_right{
      width: calc(100% - 200px);
      height: 100%;
      margin-right: 20px;

      /deep/ .vue-grid-item{
        background-color: #EBF1FE;
      }
    }
    .backgroundImage_div{
      width: calc(100% - 260px);
      height: calc(100% - 70px);
      margin-right: 20px;
      z-index: -999;
      opacity: 0.5;
      position: absolute;
      top: 0;
      left: 240px;
      right: 0;

      background-repeat: no-repeat;
      background-size: cover;
    }
  }
}
.grid-item-container{
  width: 100%;height: 100%;
  .grid-item-container-line1{
    width: calc(100% - 6px);height: 8px;background-color: #CBCBCB;
    border-radius: 4px;margin: 0 3px;margin-top: 2px;
  }
  .grid-item-container-line2{
    width: calc(100% - 20px);
    height: 20%;
    margin: 0 10px;
    display: flex;align-items: center;
    font-size: 20px;
  }
  .grid-item-container-line3{
    width: calc(100% - 20px);
    margin: 0 10px;
    height: 20%;
    display: flex;align-items: center;
    font-size: 20px;
  }
  .grid-item-container-line4{
    width: calc(100% - 20px);
    margin: 0 10px;
    margin-top: 10px;
    height: calc(60% - 30px);
    display: flex;align-items: center;justify-content: space-between;
    .grid-item-container-line4-img{
      width: calc(50% - 5px);height: 100%;
      img{
        width: 100%;
        height: 100%;
      }
    }
    .grid-item-container-line4-status{
      width: calc(50% - 5px);height: 100%;
      display: flex;justify-content: center;align-items: center;
      background-color: darkgrey;
    }
    .noPic{
      width: 100%;
    }
  }
  .remove {
    position: absolute;
    right: 2px;
    top: -5px;
    cursor: pointer;
  }
}
</style>
